#include <iostream>

#include "CSmartPtr.h"

using namespace std;

class CSimpleObject
{
private:
	char *name;

public:
	CSimpleObject(char *aname) {
		name = aname;
		cout << "\t(+)create " << name << endl;
	};
	virtual ~CSimpleObject() {
		cout << "\t(-)delete " << name << endl;
	};

	void print() {
		cout << "\t+obj[" << name << "] will be called by print()" << endl;
	};
};

CSmartPtr<CSimpleObject> f1(char *name)
{
	return CSmartPtr<CSimpleObject>(new CSimpleObject(name));
}

void f2(CSimpleObject *o)
{
	o->print();
}

int main(int argc, char *argv[])
{
	cout << "## obj[1] will be created" << endl;
	CSmartPtr<CSimpleObject> ptr1(new CSimpleObject("1"));
	cout << "## obj[2] will be created" << endl;
	CSmartPtr<CSimpleObject> ptr2(new CSimpleObject("2"));

	cout << "## obj[1] will be destroyed, and point to obj[2]" << endl;
	ptr1 = ptr2;
	cout << "## obj[2] won't be destroyed, and point to obj[3]" << endl;
	ptr2 = f1("3");
	cout << "## obj[3] will be destroyed with NULL" << endl;
	ptr2 = NULL;
	cout << "## obj[2] will be called to invoke its function" << endl;
	f2(ptr1);

	// useage in error
	//--------------------------------------------------------------------------------
/*
	CSimpleObject o1;
	ptr1 = &o1; // o1 is on stack, so is has error

	CSimpleObject *o2 = new CSimpleObject();
	ptr1 = o2;
	ptr2 = o2; // since CSimpleObject doesn't implement IRefCount class, it has error
	// ptr1 = ptr2 // <== so it will be good
*/
	//--------------------------------------------------------------------------------

	CSmartPtr<int> a(new int);
	CSmartPtr<int> b(new int);

	*a = 5;
	*b = 6;

	cout << "\t\ta = " << *a << ", b = " << *b << endl;


	cout << "## finally, obj[2] will be destroyed" << endl;
	return 0;
}
